package com.hy;

/**
 * Created With IntelliJ IDEA.
 * Descriptions:从链表中删去总和值为零的连续节点
 * 给你一个链表的头节点head，请你编写代码，反复删去链表中由 总和值为 0 的连续节点组成的序列，直到不存在这样的序列为止。
 *
 * 删除完毕后，请你返回最终结果链表的头节点。
 *
 *
 * author: Mr.Du
 * Date: 2023/6/16
 * Time: 10:56
 */
public class RemoveZeroSumSublists {

    public ListNode removeZeroSumSublists(ListNode head) {
        ListNode cur = head, tmp = head;
        int len = 0;
        while(cur != null){
            cur = cur.next;
            len++;
        }
        int[] nums = new int[len];
        int index = 0;
        while(tmp != null){
            nums[index++] = tmp.val;
            tmp = tmp.next;
        }
        boolean[] tf = new boolean[len];
        int start = 0, end = 0;
        for(int i = 0;i < len;i++){
            int res = 0;
            if(nums[i] == 0){
                tf[i] = true;
            }
            if(!tf[i]){
                start = i;
                res += nums[i];
                for(int j = i + 1;j < len;j++){
                    if(!tf[j]){
                        res += nums[j];
                        if(res == 0){
                            while(start <= j){
                                tf[start++] = true;
                            }
                            break;
                        }
                    }
                }
            }
        }
        ListNode dummy = new ListNode(0);
        ListNode curr = dummy;
        for (int i = 0;i < len;i++) {
            if(!tf[i]){
                ListNode newNode = new ListNode(nums[i]);
                curr.next = newNode;
                curr = curr.next;
            }

        }

        return dummy.next;
    }
}
